using System;

using Cookbook.Common;
using Cookbook.Services.Core.Domain;
using Cookbook.Services.Core.ExceptionHandling;

namespace Cookbook.Services.Core.Persistency.NHibernate.ExceptionHandling
{
    internal class CookbookExceptionPolicy : INHibernateExceptionPolicy
    {
        /// <summary>
        /// Processes the NHibernate exception and returns a possibily wrapping exception.
        /// </summary>
        public Exception Process(Exception exception)
        {
            var applicationErrorException = exception as ApplicationErrorException;
            
            if ((applicationErrorException != null) &&
                (applicationErrorException.Error == ServiceError.NameCodeOrNumberIsNotUnique) &&
                    (applicationErrorException.Parameters["EntityType"].Equals(typeof (Recipe))))
            {
                exception = new RuleViolationException(CookbookRule.RecipeTitleMustBeUnique);
            }

            if ((applicationErrorException != null) &&
                (applicationErrorException.Error == ServiceError.DataSizeWasExceeded) &&
                (applicationErrorException.Parameters["EntityType"].Equals(typeof(Recipe))))
            {
                exception = new RuleViolationException(CookbookRule.RecipeTitleMustBeShort);
            }
            
            if ((applicationErrorException != null) &&
                (applicationErrorException.Error == ServiceError.RecordIsUsedByAnotherRecord) &&
                (applicationErrorException.Parameters["EntityType"].Equals(typeof(Product))))
            {
                exception = new RuleViolationException(CookbookRule.ProductCannotBeRemovedIfStillUsed);
            }

            return exception;
        }
    }
}